/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.icee.myth.gm.activity;

import com.icee.myth.gm.client.GameServerClient;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author liuxianke
 */
public class Activity {
    public final GameServerClient gameServerClient;
    public final LinkedList<BroadcastInfo> broadcasts;
    protected long prevTime;    // 最后一次update的时间

    public Activity(GameServerClient server, ActivityStaticInfo staticInfo, long currentTime) {
        this.gameServerClient = server;
        // 广播
        broadcasts = ((staticInfo.broadcastInfos != null) && (staticInfo.broadcastInfos.length > 0))?new LinkedList<BroadcastInfo>(Arrays.asList(staticInfo.broadcastInfos)):null;
        
        this.prevTime = currentTime;
    }

    // 当活动结束返回fasle
    public boolean update(long currentTime) {
        List<Integer> onlinePlayerIds = null;
        
        // 处理广播
        if (broadcasts != null) {
            for (Iterator<BroadcastInfo> itor = broadcasts.iterator(); itor.hasNext();) {
                BroadcastInfo broadcast = itor.next();
                if (prevTime < broadcast.endTime) { // 判断该广播是否结束
                    if (prevTime >= broadcast.startTime) {   // 判断该广播是否开始（注意：不能用currentTime来作开始判断）
                        // 查看当前时间与先前时间是否跨越某一逻辑点
                        int prevLogicPoint = (int)((prevTime - broadcast.startTime) / broadcast.period);
                        int currentLogicPoint = (int)((currentTime - broadcast.startTime) / broadcast.period);
                        if (currentLogicPoint > prevLogicPoint) {
                            // 执行广播逻辑
                            gameServerClient.broadcast(broadcast.message);
                        }
                    }
                } else {
                    itor.remove();
                }
            }
        }

        prevTime = currentTime;

        return ((broadcasts != null) && !broadcasts.isEmpty());
    }
}
